package com.ruoyi.business.communication;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.business.communication.domain.SlotStatus;
import com.ruoyi.business.communication.listener.DeviceStatusListener;
import com.ruoyi.business.device.domain.Device;
import com.ruoyi.business.device.service.IDeviceService;
import com.ruoyi.common.core.redis.RedisCache;

import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;


import com.ruoyi.business.communication.listener.impl.RelayDeviceStatusListener;
import com.ruoyi.business.workshop.service.WorkshopManagementService;
import com.ruoyi.business.alarm.listener.DoorAlarmListener;
/**
 * 设备调度服务：加载数据库设备并缓存到Redis
 * - 使用Hash结构：大Key="Device"，小Key=设备中继号(deviceRelayCode)，value=Device对象
 * - 通过若依框架的定时任务系统管理定时任务
 */
@Service
public class DeviceScheduledService {
    //采用Logger输出日志
    private static final Logger logger = LoggerFactory.getLogger(DeviceScheduledService.class);
    private static final String REDIS_DEVICE_HASH_KEY = "Device";

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private DeviceCommunicationService deviceCommunicationService;

    @Autowired
    private WorkshopManagementService workshopManagementService;
    
    @Autowired
    private RelayDeviceStatusListener redisDeviceStatusListener;
    
    @Autowired
    private DoorAlarmListener doorAlarmListener;

    private List<DeviceStatusListener> deviceStatusListeners = new ArrayList<>();

    /**
     * 全量加载设备到Redis Hash
     */
    @PostConstruct
    public void loadAllDevicesToRedis() {
        List<Device> devices = deviceService.selectDeviceList(new Device());
        Map<String, Device> map = new HashMap<>();
        for (Device d : devices) {
            if (d.getDeviceRelayCode() != null && !d.getDeviceRelayCode().isEmpty()) {
                map.put(d.getDeviceRelayCode(), d);
            }
        }
        if (!map.isEmpty()) {
            redisCache.setCacheMap(REDIS_DEVICE_HASH_KEY, map);
        }

        deviceStatusListeners.add(redisDeviceStatusListener);
        deviceStatusListeners.add(workshopManagementService);
        deviceStatusListeners.add(doorAlarmListener);
    }

    /**
     * 从Redis按中继号获取设备
     */
    public Device getDeviceByRelayCode(String relayCode) {
        if (relayCode == null) return null;
        return redisCache.getCacheMapValue(REDIS_DEVICE_HASH_KEY, relayCode);
    }

    /**
     * Device1定时任务调用
     */
    public void pollDeviceStatus(String relayCode){
        // 这里可以添加具体的设备状态检查逻辑
        // 例如：检查所有设备连接状态、读取设备数据等
        logger.debug("pollDeviceStatus-设备状态检查任务执行-当前线程: " + Thread.currentThread().getName());
        //获取设备1
        Device device = getDeviceByRelayCode(relayCode);
        if (device != null) {
            //检查设备1状态
            List<SlotStatus> slotStatusList = 
                deviceCommunicationService.readSlotStatus(device);
            //记录日志
            logger.debug("pollDeviceStatus-设备状态检查任务执行-设备: " + device.getDeviceRelayCode() + " 槽位数量: " + slotStatusList.size());

            // 这里采用发布订阅模式，将数据发送给多个监听器
            // 假设有一个监听器接口 DeviceStatusListener 和监听器列表 deviceStatusListeners
            if (slotStatusList != null && !slotStatusList.isEmpty()) {
                // 通知所有监听器
                for (DeviceStatusListener listener : deviceStatusListeners) {
                    try {
                        listener.onStatusUpdate(device, slotStatusList);
                    } catch (Exception e) {
                        logger.error("通知监听器时发生异常: {}", e.getMessage());
                    }
                }
            }
        }
    }


}


